import { Card, Form, Input, Modal, Space, Button, Segmented, message } from 'antd';
import Table, { ColumnsType } from 'antd/es/table';
import { useState, useEffect } from 'react';

import commonService from '@/api/services/commonService';
import { useCommon } from '@/hooks/common';
import useUserStore from '@/store/userStore';

export default function CouponPage() {
  const uri = 'coupon';
  const cateName = '优惠券';
  const {
    data = {},
    query,
    setQuery,
    ModalPros,
    // searchForm,
    onCreate,
    // onSearchFormReset,
    // onSearch,
    handleChange,
  } = useCommon({ status: '0' }, uri, {
    des: '',
    id: 0,
    code: '',
    expireTime: '',
    sort: 1,
    status: '',
    fullMoney: '',
    money: '',
  });

  const [current, setCurrent] = useState<string>('待领取');
  const [validList, setValidList] = useState<any>([]);

  const getValidList = () => {
    commonService.getCustomApi('/common/couponlib/getValidList', {}).then((res: any) => {
      setValidList(res || []);
    });
  };

  useEffect(() => {
    getValidList();
  }, []);

  const handleTab = (e: any) => {
    setCurrent(e);
    if (e === '待领取') {
      getValidList();
    } else {
      setQuery({ ...query, pageNo: 1, status: e });
    }
  };

  const columns: ColumnsType<any> = [
    { title: 'ID', dataIndex: 'id', align: 'center', width: 60 },
    { title: '优惠券码', dataIndex: 'code', align: 'center', width: 60 },
    {
      title: '金额',
      dataIndex: 'money',
      align: 'center',
      width: 60,
      render: (val) => <div>{(val / 100).toFixed(2)}</div>,
    },
    {
      title: '满多少使用',
      dataIndex: 'fullMoney',
      align: 'center',
      width: 120,
      render: (val, record) => <div>{((val || record.fulMoney) / 100).toFixed(2)}</div>,
    },
    { title: '过期时间', dataIndex: 'expireTime', align: 'center', width: 140 },
    {
      title: '状态',
      dataIndex: 'status',
      align: 'center',
      width: 120,
      render: (status) => <div>{status === 0 ? '未使用' : '已使用'}</div>,
    },
    { title: '说明', dataIndex: 'des', align: 'center', width: 200 },
  ];

  const receive = (coupon: any) => {
    const { userToken } = useUserStore.getState();
    if (userToken.accessToken) {
      commonService.getCustomApi('/member/coupon/receive', { couponId: coupon.id }).then(() => {
        message.success('领取成功！');
      });
    } else {
      useUserStore.getState().actions.setShowLogin(true);
    }
  };

  return (
    <Space direction="vertical" size="large" className="w-full">
      {/* <Card>
        <Form form={searchForm} onFinish={onSearch}>
          <Row gutter={[16, 16]}>
            <Col span={8} lg={6}>
              <Form.Item<any> label="券码" name="code" className="!mb-0">
                <Input />
              </Form.Item>
            </Col>
            <Col span={24} lg={12}>
              <div className="flex justify-end gap-[10px]">
                <Button onClick={() => onCreate()}>领取</Button>
                <Button onClick={onSearchFormReset}>重置</Button>
                <Button type="primary" htmlType="submit">
                  查询
                </Button>
              </div>
            </Col>
          </Row>
        </Form>
      </Card> */}

      <Card title={cateName} bordered={false}>
        <div className="mb-[20px] flex items-center justify-between">
          <Segmented
            value={current}
            options={[
              {
                value: '待领取',
                label: (
                  <div className="flex h-[44px] w-[124px] items-center justify-center text-[20px]">
                    待领取
                  </div>
                ),
              },
              {
                value: '0',
                label: (
                  <div className="flex h-[44px] w-[124px] items-center justify-center text-[20px]">
                    待使用
                  </div>
                ),
              },
              {
                value: '1',
                label: (
                  <div className="flex h-[44px] w-[124px] items-center justify-center text-[20px]">
                    已使用
                  </div>
                ),
              },
              {
                value: '2',
                label: (
                  <div className="flex h-[44px] w-[124px] items-center justify-center text-[20px]">
                    已过期
                  </div>
                ),
              },
            ]}
            onChange={handleTab}
          />
          <Button className="h-[54px] w-[140px]" type="primary" onClick={() => onCreate({})}>
            添加优惠券
          </Button>
        </div>
        {current === '待领取' ? (
          <Table
            rowKey="id"
            size="small"
            pagination={false}
            scroll={{ x: 'max-content' }}
            columns={columns.concat([
              {
                title: '操作',
                key: 'operation',
                align: 'center',
                width: 100,
                render: (_, record) => (
                  <Button className="w-[60px]" type="primary" ghost onClick={() => receive(record)}>
                    领取
                  </Button>
                ),
              },
            ])}
            dataSource={validList}
          />
        ) : (
          <Table
            rowKey="id"
            size="small"
            pagination={{ total: data.totalCount }}
            scroll={{ x: 'max-content' }}
            columns={columns}
            dataSource={data.list}
            onChange={handleChange}
          />
        )}
      </Card>

      <CommonModal {...ModalPros} />
    </Space>
  );
}

function CommonModal({ show, formValue, onOk, onCancel }: any) {
  const [form] = Form.useForm();
  const handleOk = async () => {
    const params = form.getFieldsValue();
    await commonService.getCustomApi('/member/coupon/exchanges', {
      code: params.code,
    });
    onOk({ doNull: true });
  };
  useEffect(() => {
    form.setFieldsValue({ ...formValue });
  }, [formValue, form]);
  return (
    <Modal title="优惠券兑换" open={show} onOk={() => handleOk()} onCancel={onCancel} centered>
      <Form initialValues={formValue} form={form} layout="horizontal">
        <Form.Item<any> label="券码" name="code" required>
          <Input />
        </Form.Item>
      </Form>
    </Modal>
  );
}
